package com.tmanager.web.services;

import org.json.JSONObject;

import com.google.inject.Inject;
import com.tmanager.persistence.dao.ActivityDAO;
import com.tmanager.persistence.dao.UserDAO;
import com.tmanager.persistence.entity.Activity;
import com.tmanager.persistence.entity.ActivityType;
import com.tmanager.persistence.entity.User;
import com.tmanager.persistence.tx.Transactional;

public class AddedActivityService {
	@Inject
	private ActivityDAO activityDAO;
	@Inject
	private UserDAO userDAO;

	

	Activity createActivity(JSONObject json,long userId){
		if (json==null){
			return null;
		}
		Activity activity = new Activity();
		activity.setUserId(userId);
		activity.setActivityId(json.optLong(Activity.JSON_ACTIVITY_ID));
		activity.setName(json.optString(Activity.JSON_NAME));
		activity.setType(ActivityType.convert(json.optInt(Activity.JSON_TYPE)));
		activity.setTimestamp(json.optLong(Activity.JSON_TIMESTAMP));
		if (json.has(Activity.JSON_SUB_ACTIVITY)){
			activity.setSubActivity(createActivity(json.optJSONObject(Activity.JSON_SUB_ACTIVITY),userId));
		}
		return activity;
	}
	
	@Transactional(rollbackOn = Exception.class)
	public void saveActivity(JSONObject json) {
		User user = userDAO.getUserByEmail("admin@test.com");
		Activity activity = createActivity(json,user.getId());
		activityDAO.save(activity);
	}
}
